﻿using CsvHelper.Configuration;
using Lottery.Classes;
using Lottery.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Lottery.Data
{
    class GroupRuleData
    {

        private static GroupRuleData instances = null;

        public static GroupRuleData Instances
        {
            get
            {
                if (instances == null)
                    instances = new GroupRuleData();
                return GroupRuleData.instances;
            }
        }

        internal List<GroupRule> GroupRules { get => groupRules; set => groupRules = value; }

        private TxtData<GroupRule> txtData;

        /// <summary>
        /// 中奖列表
        /// </summary>
        private List<GroupRule> groupRules = new List<GroupRule>();

        private GroupRuleData()
        {
            if (groupRules == null || groupRules.Count <= 0)
            {
                this.groupRules = this.loadGroupRules(MyResources.GetConfigPath(MyResources.GroupRuleName));
            }
        }

        public List<GroupRule> loadGroupRules(string fileName)
        {
            txtData = new TxtData<GroupRule>(fileName);
            txtData.ClassMap = typeof(GroupRuleMap);
            List<GroupRule> allGroupRules = txtData.readToObject();
            foreach (GroupRule groupRule in allGroupRules)
            {
                //剩下的数量=总数减去抽调的
                groupRule.LostNumber = groupRule.RuleNumber - WinnerData.Instances.existGiftLevel(groupRule);
            }
            return allGroupRules;
        }

        /// <summary>
        /// 通过奖品随机获取抽取规则
        /// </summary>
        /// <param name="gift"></param>
        /// <returns></returns>
        public GroupRule findRandomRuleByGift(GiftInfo gift)
        {
            var results = this.groupRules.Where(item => gift.LevelName.Equals(item.GiftLevelName));
            GroupRule rule =  results.OrderBy(_ => Guid.NewGuid()).FirstOrDefault(); 
            if(rule == null)
            {
                return new GroupRule();
            }
            return rule;
        }

        public class GroupRuleMap : ClassMap<GroupRule>
        {
            public GroupRuleMap()
            {
                Map(m => m.Company).Name("公司");
                Map(m => m.Dept).Name("部门");
                Map(m => m.GiftLevelName).Name("奖品等级");
                Map(m => m.RuleNumber).Name("数量");
                Map(m => m.LostNumber).Ignore();
            }
        }
    }
}
